import {Token} from 'token'
import {Config} from 'config'

class Base {
    constructor() {
        this.baseRestUrl = Config.restUrl;
        this.onPay = Config.onPay;
    }

    request(parms, noRefetch) {
        var that = this;
        var url = this.baseRestUrl + parms.url;
        if (parms.type) {
            parms.type = 'GET';
        }
        /*不需要再次组装地址*/
        if (parms.setUrl) {
            url = parms.url;
        }
        wx.request({
            url: url,
            data: parms.data,
            method: parms.type,
            header: {
                'content-type': 'application/json',
                'token': wx.getStorageSync('token')
            },
            success: function (res) {
                var code = res.statusCode.toString();
                var startChar = code.charAt(0);
                if (startChar == '2') {
                  parms.sCallBack && parms.sCallBack(res.data);
                } else {
                    if (data == '401') {
                        if (!noRefetch) {
                            that._refetch()
                        }
                    }
                    that._processError(res);
                    parms.eCallBack && parms.eCallBack(res.data)
                }
            },
            fail: function (err) {
                that._processError(err);
            }
        })
    }

    _processError(err) {
        console.log(err);
    }

    _refetch(param) {
        var token = new Token();
        token.getTokenFromServer(token => {
            this.request(param, true);
        })
    }

    // 获取元素上绑定的值
    getDataSet(event, key) {
        return event.currentTarget.dataset[key];
    }
}

export {Base}
